//导入express包
const express = require('express')
//创建实例对象
const app=express()

//导入cors中间件
const cors=require('cors')

app.use(cors())

//配置解析表单数据中间件，这个中间件只能解析application/x-www-form-urlencoded 格式的表单
// app.use(express.urlencoded({extended:false}))
const formidable = require('express-formidable')
app.use(formidable())
//在路由模块之前，封装res.R函数
app.use((req,res,next)=>{
    //status默认400
    //err为错误对象或者错误字符串
    res.R=function(err,status=400){
        res.send({
            status,
            message:err instanceof Error ? err.message:err,
        })
    }
    next()
})
//在路由之前解析配置Token的中间件
const {expressjwt:expressJWT}=require('express-jwt')
const config=require('./config')
app.use(expressJWT({secret:config.jwtSecretKey,algorithms:['HS256']}).unless({path:[/^\/user/,/^\/source/,/^\/tag/,/^\/other/,/^\/blog\/readblog/,]}))

//导入并使用路由模块
const userRouter=require('./router/user') 
const Joi = require('@hapi/joi')
app.use('/user',userRouter)
//导入并使用模块
const userinfoRouter=require('./router/userinfo')
app.use('/my',userinfoRouter)
//导入路由
const sourceRouter=require("./router/source")
app.use('/source',sourceRouter)
//导入路由
const commentRouter=require("./router/comment")
app.use('/comment',commentRouter)
//导入标签模块路由哦
const tagRouter=require('./router/tag')
app.use('/tag',tagRouter)
//导入其他用户模块路由哦
const otherRouter=require('./router/otheruser')
app.use('/other',otherRouter)
//导入收藏模块
const storeRouter=require("./router/store")
app.use('/my',storeRouter)
//博客模块
const blogRouter=require("./router/blog")
app.use('/blog',blogRouter)
//点赞模块
const islike=require('./router/islike')
app.use("/my",islike)
//定义错误级别中间件
app.use((err,req,res,next)=>{
    if(err instanceof Joi.ValidationError) return res.R(err)
    //身份认证失败
    if(err.name === "UnauthorizedError") return res.R("身份验证失败！",401)
    res.R(err)
})

//启动服务器与3000端口
app.listen(3000,()=>{
    console.log("server running at http://127.0.0.1:3000");
})
